package com.qingluan.dd;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.qingluan.Database.Personal_Info_database;
import com.qingluan.geo.BaiduLocationServer;
import com.qingluan.geo.GeoGetAsync;
import com.qingluan.geo.GeoGetAsync.GetPoninterAsyncListener;
import com.qingluan.geo.GeoPersonalOverlay;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MapModel extends Activity {
	private BMapManager mapManager;
	private MapView mapView;
	private MapController mapController;
	
	//context argu raea
	private Context context_this_activity;
	private static String tag = MapModel.class.getName();
	
	//Geo points atgu 
	private GeoGetAsync GeoThread ;
	private String this_user_name;
	private List<HashMap<String, String>> tagsInfo;
	private HashMap<String, GeoPoint> tagsMap;
	private String uid;
	private GeoPersonalOverlay overlay ;
	private Drawable mark;
	
	private static String HASH_LAT = "lat";
	private static String HASH_LON = "lon";
	private static String HASH_MISSION_NAME = "mission_name";
	private static String UP_NAME = "up_name";

	
	private BaiduLocationServer locationServer;
	private GeoPoint Now_Place;
	//token area
	private String token_id;
	private String token_key;
	private JSONArray all_misison;
	
	//threada argu 
	private ReentrantLock Lock;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mapManager = new BMapManager(getApplication());
		mapManager.init("Ei38G5wOcSolTE7LXhDf0eNj",null);
		setContentView(R.layout.activity_map_model);
		context_this_activity = getApplicationContext();
	
		uid = getIntent().getExtras().getString("uid");
		token_id = getIntent().getExtras().getString("token_id");
		token_key = getIntent().getExtras().getString("token_key");
		
		this_user_name = new Personal_Info_database(context_this_activity).searchName(uid);
		tagsMap = new HashMap<String, GeoPoint>();
		tagsInfo = new ArrayList<HashMap<String,String>>(); 
		InitMap();
		InitLocation();
		
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		mapView.destroy();
		if (mapManager!= null){
			try{
				mapManager.destroy();
				mapManager = null;
			}catch (NullPointerException e){
				Log.d(tag, e.toString());
			}
		}
		super.onDestroy();

	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.d(tag, "pause");
		
		mapView.onPause();  
		if (mapManager != null){
			 mapManager.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.d(tag,"resume");
		mapView.onResume();
		if (mapManager != null){
			mapManager.start();
		}
//		mapController.setZoom(12);
		if (Now_Place != null){
			mapController.animateTo(Now_Place);
		}
		GeoThread.run();
		super.onResume();
	}
	private void  InitMap(){
		mapView = (MapView) findViewById(R.id.action_map_model);
		mapController = mapView.getController();
		
		mark = getResources().getDrawable(R.drawable.mark);
		mark.setBounds(0, 0, mark.getIntrinsicWidth(), mark.getIntrinsicHeight());
		overlay = new GeoPersonalOverlay(mark, mapView);
		overlay.setCallActivity(MapModel.this,OnePointDetailInfo.class);
		overlay.setMapController(mapController);
		
		
		GeoThread = new GeoGetAsync(context_this_activity, this_user_name, token_id, token_key);
		GeoThread.setGetPointListener(new GetPoninterAsyncListener() {
			
			@Override
			public void onGetPoint(JSONArray info) {
				Log.d(tag,"loading ...data ... all : "+String.valueOf(info.length()));
				all_misison = info;
				try {
					collected_data();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				deal_with_point();
			}

			@Override
			public void errorLog(String error) {
				// TODO Auto-generated method stub
				Toast.makeText(context_this_activity, error, Toast.LENGTH_SHORT).show();
			}
		});
		

		
		
	}
	
	private void InitLocation(){
		locationServer = new BaiduLocationServer(context_this_activity);
		locationServer.RunLocationServer(new BDLocationListener(){

			@Override
			public void onReceiveLocation(BDLocation point) {
				// TODO Auto-generated method stub
				String  onepoint = point.getCity();
				
				GeoPoint this_place = new GeoPoint((int)(point.getLatitude() *1E6), (int)(point.getLongitude() *1E6));
				Now_Place = this_place;
				mapController.animateTo(this_place);
				BaiduLocationServer.turn +=1;
				locationServer.OFF(2);
				Toast.makeText(context_this_activity, onepoint, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onReceivePoi(BDLocation arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}
	private void collected_data() throws JSONException{
		if (all_misison != null){
			for (int i = 0 ; i< all_misison.length(); i++){
				JSONObject json = all_misison.getJSONObject(i);
				Log.d(tag, "one item :"+ json);
				String mission_id = json.getString("mission_id");
				GeoGetAsync.IDS.add(mission_id);
				
				String mission_name = json.getString(MapModel.HASH_MISSION_NAME);
				String up_name = json.getString(MapModel.UP_NAME);
				int lat = json.getInt(HASH_LAT);
				int lon = json.getInt(HASH_LON);
				Log.d(tag,"lat :"+String.valueOf(lat)+"\nlon"+String.valueOf(lon));
				GeoPoint onePoint = new GeoPoint(lat, lon);
				HashMap<String , String> oneItem = new HashMap<String, String>();
				oneItem.put(HASH_MISSION_NAME, mission_name);
				oneItem.put(UP_NAME, up_name);
				
				Log.d(tag, "mission name:"+mission_name);
				Log.d(tag, "up name :"+up_name);
				tagsMap.put(mission_name, onePoint);
				tagsInfo.add(oneItem);
				
				//重绘制地图
				
				
			}
		}
	}
	
	private void deal_with_point(){
		Log.d(tag,"start..draw picture "+String.valueOf(tagsInfo.size()));
		mapView.getOverlays().clear();
		for (HashMap<String, String> oneItem : tagsInfo){
			Log.d(tag,"loading ...data ...");
//			Log.d(tag,oneItem.get("name"));
			OverlayItem item = new OverlayItem(tagsMap.get(oneItem.get(HASH_MISSION_NAME)), oneItem.get(HASH_MISSION_NAME), oneItem.get(UP_NAME));
			item.setMarker(mark);
			overlay.addItem(item);
		}
		
		
		mapView.getOverlays().add(overlay);
		mapController.setZoom(14);
		mapView.refresh();
	}
	
	
}
